38
Beginner’s Guide to Code Algorithms
38
Cell reference
Array reference
Value
(9,1)
cantbelist(9,1,1)
1
(9,1)
cantbelist(9,1,2)
2
(9,1)
cantbelist(9,1,3)
3
(9,1)
cantbelist(9,1,4)
4
(9,1)
cantbelist(9,1,5)
5
(9,1)
cantbelist(9,1,6)
7
(9,1)
cantbelist(9,1,7)
blank
(9,1)
cantbelist(9,1,8)
blank
(9,1)
cantbelist(9,1,9)
blank
Note that if we had two more numbers in the “cantbelist” array, we would be able
to complete the cell.
This is the basic algorithm we need to solve for all the missing cells. As we look at
every row, column, and 3 by 3 grid, we keep building the “cantbelist” since each cell
may be influenced by the row, column, or 3 by 3 grid that it belongs to. As we build
this, we stop when there is only one out of nine items left in the “cantbelist”. This,
therefore, must be the missing number!
This is how a human user solves the puzzle as well. The difference in using a com
puter is as follows:
• The computer can do it a lot faster.
• There are no chance of making mistakes.
• Computer can perform this task multiple times to refine the search for the missing
number, since the discovery of one cell increases the entries in the “cantbelist” for
other cells, thus improving the chances of finding missing numbers.
3.1 THE BASIC CODE FOR SOLVING A SUDOKU
Here is how the basic code can be written:
STEP 1
Define the variables, initialize the cantbelist to 0 and set up the structure for
building cantbelist.
We use variable “sbox” to store the current value of each cell in the 9 by 9 grid.
Row is i, column is j.
Public cantbelist() As Integer
Public sbox(9, 9)
For i = 1 To 9
For j = 1 To 9
sbox(i, j) = Cells(i, j)
Next j
Next i